<?php
@include_once('conn.php');


$userid = $_GET["userid"];
$goodsid = $_GET["goodsid"];
$goodsname = $_GET["goodsname"];
$goodsprice = $_GET["goodsprice"];
$buynum = $_GET["buynum"];
$goodsimg = $_GET["goodsimg"];

/* $uname = 'aa';
    $goods_num = 2;
    $goods_id = 2; */

$obj = [];

if ($userid && $goodsid && $buynum) {
    // 判断购物车中  该用户是否已经加入了该商品
    $sql = "select * from cart_info where userid = '$userid' and goodsid = $goodsid";
    $result = mysqli_query($conn, $sql);
    $arr = mysqli_fetch_array($result);
    if ($arr) {
        // 这里表示用户已经加入了该商品
        //   只需要修改数量即可    num = num + 2 在原来的基础上加2
        $sql = "update cart_info set buynum = buynum + $buynum where userid = '$userid' and goodsid = $goodsid ";
        mysqli_query($conn, $sql);
        // 得到受影响的行数
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '成功加入购物车';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '失败加入购物车';
        }
    } else {
        // 这里表示用户没有加入该商品
        //   插入新的数据
        $sql = "insert into cart_info (userid,goodsid,goodsname,goodsprice,buynum,goodsimg) values ('$userid','$goodsid','$goodsname','$goodsprice','$buynum','$goodsimg')";
        mysqli_query($conn, $sql);
        // 得到受影响的行数
        $rows = mysqli_affected_rows($conn);
        if ($rows > 0) {
            $obj['status'] = true;
            $obj['msg'] = '成功加入购物车';
        } else {
            $obj['status'] = false;
            $obj['msg'] = '失败加入购物车';
        }
    }
} else {
    $obj['status'] = false;
    $obj['msg'] = '数据库请求失败';
}

echo json_encode($obj);
